<script setup>
import { ref, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import requestUtil from '@/util/request'
import { ElMessage } from 'element-plus'

// 数据定义
const trendData = ref([])
const selectedDepts = ref([])
const selectedMonth = ref('')
const allDepartments = ref([])
const allMonths = ref([])
const trendChart = ref(null)
const compareChart = ref(null)
const chartInstance = ref(null)
const compareChartInstance = ref(null)
const loading = ref(false)

// 获取趋势数据
const fetchTrendData = async () => {
  loading.value = true
  try {
    const res = await requestUtil.post('sys/jixiaokaohe/departments/trend')
    const data = res.data
    
    if (data.code === 200) {
      trendData.value = data.list || []
      
      // 提取所有部门并确保唯一性
      allDepartments.value = [...new Set(trendData.value.map(item => item.departmentName))]
      // 提取所有月份并确保唯一性
      allMonths.value = [...new Set(trendData.value.map(item => item.month))].sort()
      
      // 默认选择前2个有数据的部门和最新月份
      selectedDepts.value = allDepartments.value.slice(0, 99)
      selectedMonth.value = allMonths.value[allMonths.value.length - 1] || ''
      
      await nextTick()
      initTrendChart()
      initCompareChart()
    } else {
      throw new Error(data.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取趋势数据失败:', error)
    ElMessage.error(error.message || '数据加载失败')
  } finally {
    loading.value = false
  }
}

// 初始化趋势图表
const initTrendChart = () => {
  // 安全检查
  if (!trendData.value.length || !trendChart.value || !selectedDepts.value.length) {
    return
  }

  // 销毁旧图表
  if (chartInstance.value) {
    chartInstance.value.dispose()
    chartInstance.value = null
  }

  // 初始化新图表
  chartInstance.value = echarts.init(trendChart.value)

  // 处理数据
  const months = [...new Set(trendData.value.map(item => item.month))].sort()
  
  // 准备系列数据
  const series = selectedDepts.value.map(dept => {
    return {
      name: dept,
      type: 'line',
      data: months.map(month => {
        const record = trendData.value.find(
          item => item.departmentName === dept && item.month === month
        )
        return record ? record.avgScore : null
      }),
      symbol: 'circle',
      symbolSize: 8,
      smooth: true,
      lineStyle: {
        width: 3
      },
      // 添加标签显示
      label: {
        show: true,
        formatter: (params) => {
          const record = trendData.value.find(
            item => item.departmentName === dept && item.month === params.name
          )
          return record ? `${record.avgScore.toFixed(1)}分` : ''
        },
        position: 'top'
      }
    }
  })

  // 图表配置
  const option = {
    title: {
      text: '部门绩效趋势分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        let html = `${params[0].axisValue}<br/>`
        params.forEach(param => {
          const record = trendData.value.find(
            item => item.departmentName === param.seriesName && item.month === param.name
          )
          const count = record ? record.employeeCount : 0
          html += `
            <span style="display:inline-block;margin-right:5px;
              border-radius:10px;width:10px;height:10px;
              background-color:${param.color}"></span>
            ${param.seriesName}: ${param.data?.toFixed(1) || '0'}分 (${count}人)<br/>
          `
        })
        return html
      }
    },
    legend: {
      data: selectedDepts.value,
      bottom: 10
    },
    grid: {
      top: '15%',
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLabel: {
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '平均绩效分',
      min: 0,
      max: 100,
      axisLabel: {
        formatter: '{value}分'
      }
    },
    series: series,
    // 添加数据区域颜色
    visualMap: {
      top: 50,
      right: 10,
      pieces: [
        { gt: 90, lte: 100, color: '#52c41a' }, // 优秀
        { gt: 80, lte: 90, color: '#1890ff' }, // 良好
        { gt: 70, lte: 80, color: '#faad14' }, // 一般
        { gt: 60, lte: 70, color: '#ffec3d' }, // 合格
        { gt: 0, lte: 60, color: '#ff4d4f' },  // 不合格
        { lte: 0, color: '#bfbfbf' }            // 无数据
      ],
      outOfRange: {
        color: '#d9d9d9'
      }
    }
  }

  // 设置图表选项
  chartInstance.value.setOption(option)
}

// 初始化横向对比图表
const initCompareChart = () => {
  // 安全检查
  if (!trendData.value.length || !compareChart.value || !selectedMonth.value) {
    return
  }

  // 销毁旧图表
  if (compareChartInstance.value) {
    compareChartInstance.value.dispose()
    compareChartInstance.value = null
  }

  // 初始化新图表
  compareChartInstance.value = echarts.init(compareChart.value)

  // 准备数据
  const filteredData = trendData.value.filter(item => item.month === selectedMonth.value)
  
  // 按分数排序
  const sortedData = [...filteredData].sort((a, b) => b.avgScore - a.avgScore)
  
  // 准备系列数据
  const series = [{
    name: '平均绩效分',
    type: 'bar',
    data: sortedData.map(item => ({
      value: item.avgScore,
      itemStyle: {
        color: getScoreColor(item.avgScore)
      }
    })),
    label: {
      show: true,
      position: 'right',
      formatter: (params) => {
        const record = sortedData[params.dataIndex]
        return `${record.avgScore.toFixed(1)}分 (${record.employeeCount}人)`
      }
    }
  }]

  // 图表配置
  const option = {
    title: {
      text: `部门绩效横向对比 - ${selectedMonth.value}`,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        const record = sortedData[params[0].dataIndex]
        return `
          <div style="font-weight:bold">${record.departmentName}</div>
          平均绩效分: ${record.avgScore.toFixed(1)}分<br/>
          员工人数: ${record.employeeCount}人
        `
      }
    },
    grid: {
      top: '15%',
      left: '3%',
      right: '8%',
      bottom: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '平均绩效分',
      min: 0,
      max: 100,
      axisLabel: {
        formatter: '{value}分'
      }
    },
    yAxis: {
      type: 'category',
      data: sortedData.map(item => item.departmentName),
      axisLabel: {
        interval: 0,
        rotate: 0
      }
    },
    series: series
  }

  // 设置图表选项
  compareChartInstance.value.setOption(option)
}

// 根据分数获取颜色
const getScoreColor = (score) => {
  if (score > 90) return '#52c41a'  // 优秀
  if (score > 80) return '#1890ff'  // 良好
  if (score > 70) return '#faad14'  // 一般
  if (score > 60) return '#ffec3d'  // 合格
  if (score > 0) return '#ff4d4f'   // 不合格
  return '#bfbfbf'                  // 无数据
}

// 监听部门选择变化
watch(selectedDepts, (newVal) => {
  if (newVal && newVal.length > 0) {
    initTrendChart()
  }
}, { deep: true })

// 监听月份选择变化
watch(selectedMonth, (newVal) => {
  if (newVal) {
    initCompareChart()
  }
})

// 生命周期
onMounted(() => {
  fetchTrendData()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose()
  }
  if (compareChartInstance.value) {
    compareChartInstance.value.dispose()
  }
  window.removeEventListener('resize', handleResize)
})

// 窗口大小变化时重绘图表
const handleResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize()
  }
  if (compareChartInstance.value) {
    compareChartInstance.value.resize()
  }
}
</script>

<template>
  <div class="trend-analysis-container">
    <el-card shadow="never" class="chart-card">
      <template #header>
        <span>部门绩效趋势分析</span>
        <el-select 
          v-model="selectedDepts" 
          multiple 
          placeholder="选择对比部门"
          style="width: 300px; margin-left: 20px;"
        >
          <el-option
            v-for="dept in allDepartments"
            :key="dept"
            :label="dept"
            :value="dept"
          />
        </el-select>
      </template>

      <div ref="trendChart" style="width: 100%; height: 500px;"></div>
    </el-card>

    <el-card shadow="never" class="chart-card" style="margin-top: 20px;">
      <template #header>
        <span>部门绩效横向对比</span>
        <el-select 
          v-model="selectedMonth" 
          placeholder="选择月份"
          style="width: 200px; margin-left: 20px;"
        >
          <el-option
            v-for="month in allMonths"
            :key="month"
            :label="month"
            :value="month"
          />
        </el-select>
      </template>

      <div ref="compareChart" style="width: 100%; height: 500px;"></div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.trend-analysis-container {
  padding: 20px;
  background-color: #f5f7fa;

  .chart-card {
    border-radius: 4px;
    border: none;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    ::v-deep .el-card__header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 15px 20px;
      border-bottom: 1px solid #ebeef5;
    }
  }
}
</style>